package com.lsp.lib_uikit.commonrecycler.adapter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import com.lsp.lib_uikit.commonrecycler.rvitem.RvListItem;

/**
 * 多布局recyclerview   需要首先调用addItemType添加各种类型对应的layout
 *
 * 实现 {@link #getDefItemViewType(int)} 方法  获取每个item对应type
 *
 * 如果可以把获取到的数据实现共同的基类,并提供itemType   可以修改本类  <D  extends BaseBean> 并在
 * {@link #getDefItemViewType(int)} 获取type
 *
 * @author lsp
 * @created 16/7/25 14:24
 */
public abstract class MultiRvAdapter<D> extends BasicRvAdapter<D> {

  private Context mContext;

  public MultiRvAdapter(Context mContext) {
    super(mContext);
    this.mContext = mContext;
  }

  private SparseArray layouts;

  @Override public RecyclerView.ViewHolder onCreateDefViewHolder(ViewGroup parent, int viewType) {
    RvListItem<D> view =
        (RvListItem<D>) LayoutInflater.from(mContext).inflate(getLayoutId(viewType), parent, false);

    return new CommonHolder(view);
  }

  @Override protected void onDefBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
    if (holder == null) {
      return;
    }
    final RvListItem<D> view = (RvListItem<D>) holder.itemView;
    view.setFirst(position == 0);
    view.setPosition(position);
    view.setLast(position == getItemCount() - 1);
    view.attachData(getAllList().get(position));
  }

  public abstract int getDefItemViewType(int position);

  /**
   * 添加多种类型item对应的布局
   */
  public void addItemType(int type, int layoutResId) {

    if (layouts == null) {
      layouts = new SparseArray();
    }
    layouts.put(type, Integer.valueOf(layoutResId));
  }

  /**
   * 通过viewtype得到对应的布局文件
   */
  protected int getLayoutId(int viewType) {
    return ((Integer) (layouts.get(viewType))).intValue();
  }
}
